package com.zy.hospitalward_management_system.controller;



import com.zy.hospitalward_management_system.mapper.StaffMapper;
import com.zy.hospitalward_management_system.pojo.Staff;
import com.zy.hospitalward_management_system.service.impl.StaffServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  账号相关Controller
 * </p>
 *
 * @author zy
 * @since 2021-01-23
 */
@Controller
public class LoginController {

    @Resource
    StaffServiceImpl staffService;

    /**
     * 输入用户名和密码 进行登陆操作
     * @param username 用户名
     * @param password 密码
     * @param session 当前浏览器Session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public String login(String username,String password, HttpSession session){

        Object loginUser = session.getAttribute("loginUser");
        if(loginUser!=null){
            return "登录成功!";
        }

        System.out.println("username = " + username + ", password = " + password + ", session = " + session);

        if(username.trim().equals("")||password.trim().equals("")){
            return "请输入用户名和密码！";
        }

        //调用Service层登录方法
        int flag = staffService.login(username, password, session);
        System.out.println(flag);
        switch (flag){
            case 1:
                return "登录成功!"; //进入系统主界面dashboard
            case -1:
                return "账号不存在！";
            case 0:
                return "密码错误!";
        }
        return "系统错误!";
    }

    //注销操作 移除Session
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "redirect:/";
    }

    //更新密码
    @PostMapping("/account/updatePwd")
    @ResponseBody
    public String updatePwd(String oldPwd,String newPwd,String checkPwd,HttpSession session){
        System.out.println("oldPwd = " + oldPwd + ", newPwd = " + newPwd + ", checkPwd = " + checkPwd);
        if(oldPwd.isEmpty()){
            return "原密码不能为空!";
        }
        if(newPwd.isEmpty()){
            return "新密码不能为空!";
        }
        if(checkPwd.isEmpty()){
            return "确认密码不能为空!";
        }

        if(!newPwd.equals(checkPwd)){
            return "确认密码不一致!";
        }

        Staff staff = (Staff) session.getAttribute("loginUser");
        if(!oldPwd.equals(staff.getStaffPassword())){
            return "原密码不正确!";
        }

        staff.setStaffPassword(newPwd);
        int i = staffService.getBaseMapper().updateById(staff);
        if(i==1){
            return "修改成功,请重新登录!";
        }else {
            return "修改失败!";
        }

    }

}

